package ipsite.controller;

import ipsite.data.Data;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;


import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

@SuppressWarnings("serial")
public class CronUpdateServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("utf-8");
	
		DBCollection coll1 = Data.data("redomain");
		DBCursor domain = coll1.find(new BasicDBObject("status",0)).limit(3);
		if(domain.size() > 0)
		{
			while (domain.hasNext()) {
				DBObject dbObject = (DBObject) domain.next();
				
				BasicDBObject set = new BasicDBObject("$set", new BasicDBObject("status",1));
				coll1.update(dbObject, set);
				try {
					setUp();
					createProducerAndSendAMessage(dbObject.get("name").toString());
				} catch (JMSException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}
	private static ActiveMQConnectionFactory connectionFactory;
    private static Connection connection;
    private static Session session;
    private static Destination destination;
    private static boolean transacted = false;
	private static void setUp() throws JMSException {
         connectionFactory = new ActiveMQConnectionFactory(
                 ActiveMQConnection.DEFAULT_USER,
                 ActiveMQConnection.DEFAULT_PASSWORD,
                 "tcp://y1s.org:61616");
         connection = connectionFactory.createConnection();
         connection.start();
         session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
         destination = session.createQueue("domain");
     }
 
     private static void createProducerAndSendAMessage(String str) throws JMSException {
   	  
         MessageProducer producer = session.createProducer(destination);
         producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
         TextMessage message = session.createTextMessage(str);
         System.out.println("Sending message: " + message.getText());
         producer.send(message);
         connection.close();
     }
}
